{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Pandas 累积统计\n",
        "\n",
        "本教程详细介绍 Pandas 中的累积统计方法：cumsum, cummax, cummin, cumprod 等。\n",
        "\n",
        "## 目录\n",
        "1. 累积和 - cumsum()\n",
        "2. 累积最大值 - cummax()\n",
        "3. 累积最小值 - cummin()\n",
        "4. 累积乘积 - cumprod()\n",
        "5. 累积平均 - expanding().mean()\n",
        "6. 综合应用\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 导入库\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import pandas as pd\n",
        "import numpy as np\n",
        "import warnings\n",
        "warnings.filterwarnings('ignore')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 1. 累积和 - cumsum()\n",
        "\n",
        "### 方法说明\n",
        "\n",
        "`cumsum()` 计算累积和（累计求和）。\n",
        "\n",
        "**语法:**\n",
        "```python\n",
        "df.cumsum(axis=None, skipna=True)\n",
        "```\n",
        "\n",
        "**主要参数:**\n",
        "- `axis`: 0(按列) 或 1(按行)，默认 0\n",
        "- `skipna`: 是否跳过NaN值，默认 True\n",
        "\n",
        "**特点:**\n",
        "- ✅ 返回累积和序列\n",
        "- ✅ 保持原始索引\n",
        "- ✅ 适用于数值型数据\n",
        "\n",
        "**适用场景:** 累计计算、时间序列分析、累计收益\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例1: 创建示例数据\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建销售数据\n",
        "df = pd.DataFrame({\n",
        "    '日期': pd.date_range('2024-01-01', periods=10, freq='D'),\n",
        "    '销售额': [100, 150, 120, 200, 180, 160, 140, 190, 210, 175],\n",
        "    '成本': [60, 90, 70, 120, 110, 95, 85, 115, 130, 105],\n",
        "    '利润': [40, 60, 50, 80, 70, 65, 55, 75, 80, 70]\n",
        "})\n",
        "\n",
        "print(\"原始数据:\")\n",
        "print(df)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例2: 计算累积和\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 计算累积销售额\n",
        "df['累计销售额'] = df['销售额'].cumsum()\n",
        "df['累计利润'] = df['利润'].cumsum()\n",
        "print(\"添加累积统计列:\")\n",
        "print(df[['日期', '销售额', '累计销售额', '利润', '累计利润']])\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 2. 累积最大值 - cummax()\n",
        "\n",
        "### 方法说明\n",
        "\n",
        "`cummax()` 计算累积最大值（到目前为止的最大值）。\n",
        "\n",
        "**特点:**\n",
        "- ✅ 返回累积最大值序列\n",
        "- ✅ 保持原始索引\n",
        "- ✅ 适用于数值型数据\n",
        "\n",
        "**适用场景:** 寻找历史最大值、峰值追踪\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 计算累积最大值\n",
        "df['累计最大销售额'] = df['销售额'].cummax()\n",
        "df['累计最大利润'] = df['利润'].cummax()\n",
        "print(\"添加累积最大值列:\")\n",
        "print(df[['日期', '销售额', '累计最大销售额', '利润', '累计最大利润']])\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 3. 累积最小值 - cummin()\n",
        "\n",
        "### 方法说明\n",
        "\n",
        "`cummin()` 计算累积最小值（到目前为止的最小值）。\n",
        "\n",
        "**特点:**\n",
        "- ✅ 返回累积最小值序列\n",
        "- ✅ 保持原始索引\n",
        "- ✅ 适用于数值型数据\n",
        "\n",
        "**适用场景:** 寻找历史最小值、谷值追踪\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 计算累积最小值\n",
        "df['累计最小销售额'] = df['销售额'].cummin()\n",
        "print(\"添加累积最小值列:\")\n",
        "print(df[['日期', '销售额', '累计最小销售额']])\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 4. 累积乘积 - cumprod()\n",
        "\n",
        "### 方法说明\n",
        "\n",
        "`cumprod()` 计算累积乘积（累计相乘）。\n",
        "\n",
        "**特点:**\n",
        "- ✅ 返回累积乘积序列\n",
        "- ✅ 保持原始索引\n",
        "- ✅ 适用于数值型数据\n",
        "\n",
        "**适用场景:** 复合增长率计算、复利计算\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建增长率数据\n",
        "growth = pd.Series([1.1, 1.05, 1.08, 1.12, 1.06, 1.09, 1.07, 1.11])\n",
        "growth_df = pd.DataFrame({\n",
        "    '期数': range(1, len(growth) + 1),\n",
        "    '增长率': growth,\n",
        "    '累积乘积': growth.cumprod()\n",
        "})\n",
        "\n",
        "print(\"增长率数据:\")\n",
        "print(growth_df)\n",
        "print(\"\\n说明: 累积乘积表示复合增长率\")\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 5. 累积平均 - expanding().mean()\n",
        "\n",
        "### 方法说明\n",
        "\n",
        "`expanding()` 创建扩展窗口，可以计算累积平均、累积标准差等。\n",
        "\n",
        "**语法:**\n",
        "```python\n",
        "df.expanding(min_periods=1).mean()\n",
        "```\n",
        "\n",
        "**特点:**\n",
        "- ✅ 返回累积平均序列\n",
        "- ✅ 可以设置最小周期数\n",
        "- ✅ 适用于时间序列分析\n",
        "\n",
        "**适用场景:** 移动平均、趋势分析\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 计算累积平均\n",
        "df['累计平均销售额'] = df['销售额'].expanding().mean()\n",
        "df['累计平均利润'] = df['利润'].expanding().mean()\n",
        "print(\"添加累积平均列:\")\n",
        "print(df[['日期', '销售额', '累计平均销售额', '利润', '累计平均利润']])\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例6: 其他扩展窗口统计\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 累积标准差\n",
        "df['累计标准差'] = df['销售额'].expanding().std()\n",
        "# 累积方差\n",
        "df['累计方差'] = df['销售额'].expanding().var()\n",
        "# 累积最大值\n",
        "df['累计最大值2'] = df['销售额'].expanding().max()\n",
        "# 累积最小值\n",
        "df['累计最小值2'] = df['销售额'].expanding().min()\n",
        "\n",
        "print(\"扩展窗口统计结果:\")\n",
        "print(df[['日期', '销售额', '累计标准差', '累计方差', '累计最大值2', '累计最小值2']])\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 6. 综合应用\n",
        "\n",
        "### 示例7: 处理缺失值\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建包含缺失值的数据\n",
        "df2 = pd.DataFrame({\n",
        "    '值': [10, np.nan, 20, 30, np.nan, 40, 50]\n",
        "})\n",
        "\n",
        "print(\"原始数据:\")\n",
        "print(df2)\n",
        "print(\"\\n累积和 (skipna=True, 默认):\")\n",
        "df2['累积和_跳过NaN'] = df2['值'].cumsum()\n",
        "print(df2)\n",
        "print(\"\\n累积和 (skipna=False):\")\n",
        "df2['累积和_保留NaN'] = df2['值'].cumsum(skipna=False)\n",
        "print(df2)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例8: 按行累积统计\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建矩阵数据\n",
        "df3 = pd.DataFrame({\n",
        "    'Q1': [100, 200, 150],\n",
        "    'Q2': [120, 180, 160],\n",
        "    'Q3': [140, 210, 170],\n",
        "    'Q4': [160, 190, 180]\n",
        "}, index=['产品A', '产品B', '产品C'])\n",
        "\n",
        "print(\"原始数据:\")\n",
        "print(df3)\n",
        "print(\"\\n按行累积和 (axis=1):\")\n",
        "print(df3.cumsum(axis=1))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 总结\n",
        "\n",
        "**累积统计方法总结:**\n",
        "1. ✅ **cumsum()**: 累积和（累计求和）\n",
        "2. ✅ **cummax()**: 累积最大值（历史最大值）\n",
        "3. ✅ **cummin()**: 累积最小值（历史最小值）\n",
        "4. ✅ **cumprod()**: 累积乘积（复合增长率）\n",
        "5. ✅ **expanding().mean()**: 累积平均（移动平均）\n",
        "6. ✅ **expanding().std()**: 累积标准差\n",
        "7. ✅ **expanding().var()**: 累积方差\n",
        "\n",
        "**最佳实践:**\n",
        "- 使用 `cumsum()` 计算累计收益、累计销售额\n",
        "- 使用 `cummax()` 和 `cummin()` 追踪峰值和谷值\n",
        "- 使用 `cumprod()` 计算复合增长率\n",
        "- 使用 `expanding()` 计算移动统计指标\n",
        "- 注意 NaN 值的处理（skipna参数）\n",
        "- 适用于时间序列数据和累积计算场景\n"
      ]
    }
  ],
  "metadata": {
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 2
}
